package me.luger.core.dao.nutz.config;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.nutz.dao.ConnCallback;
import org.nutz.dao.impl.DaoRunner;
import org.nutz.dao.impl.NutDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * NutzDaoBaseConfig
 *
 * @author luger
 * @date 2016/11/18 0018
 */
public abstract class NutzDaoBaseConfig {

    @Autowired
    protected ApplicationContext applicationContext;

    public abstract DataSource getDataSource();

    public abstract NutDao initNutzDao();

    @Bean
    @Primary
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean
    @Primary
    public ServletRegistrationBean druidServlet() {
        return new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    }

    @Bean
    @Primary
    public DaoRunner nutzDaoRunner(){
        return new DaoRunner() {
            @Override
            public void run(DataSource dataSource, ConnCallback connCallback) {
                Connection con = DataSourceUtils.getConnection(dataSource);
                try {
                    connCallback.invoke(con);
                } catch (Exception e) {
                    if (e instanceof RuntimeException)
                        throw (RuntimeException) e;
                    else
                        throw new RuntimeException(e);
                } finally {
                    DataSourceUtils.releaseConnection(con, dataSource);
                }
            }
        };
    }

    @Bean(name = "nutzDefaultTransactionManager")
    @Primary
    public DataSourceTransactionManager nutzDefaultTransactionManager() {
        return new DataSourceTransactionManager(getDataSource());
    }
}
